package application;

import java.util.HashMap;

import transport.TransportLayer;

public class ApplicationLayer {

	public static String myID;
	public static AppMessageHandler handler;
	public static final int MAXPACKETSIZE = 60000;
	public static int PACKETSIZE = MAXPACKETSIZE;
	public static HashMap<String, ReceptionWindow> receptionMap;
	public static MainWindow mainWindow;

	public static void init(String ID, String server) {
		Initiator.init(ID, server);
		myID = Initiator.myID;
		receptionMap = new HashMap<String, ReceptionWindow>();
		new Thread(new UserInterface()).start();
		handler = new AppMessageHandler();
		new Thread(handler).start();
		mainWindow = new MainWindow();
		mainWindow.setVisible(true);
	}

	public static String forgeHead(String text, String dest) {
		return dest + ":" + myID + ":HEAD:"
				+ Integer.toString((text.length() / PACKETSIZE) + 1) + ":"
				+ Integer.toString(text.length()) + ":"
				+ Integer.toString(PACKETSIZE);
	}

	public static String forgeData(String text, String dest) {
		return dest + ":" + myID + ":DATA:" + text;
	}

	public static void receive(String msg) {
		handler.handleMessage(msg);
	}

	public static void initializeReceptionWindow(String source, int length) {
		receptionMap.put(source, new ReceptionWindow(source, length));
		receptionMap.get(source).setVisible(true);
	}

	public static void updateReceptionWindow(String source, String text) {
		receptionMap.get(source).addText(text);
	}

	public static void send(String text, String dest, int mode) {
		int MSGcount = 0;
		TransportLayer.send(forgeHead(text, dest), mode);
		MSGcount++;
		int pack = PACKETSIZE;
		int i = 0;
		while (i < text.length()) {
			TransportLayer.send(forgeData(text.substring(i, Math.min(i + pack,
					text.length())), dest), mode);
			i += pack;
			MSGcount++;
		}
		System.err.println("*** " + MSGcount + " messages sent by app to "
				+ dest + " in mode " + mode + ".");
	}

}
